package com.example.yiwei.crm.view.activity.coordinationActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetAreData;
import com.example.yiwei.crm.data.GetDock;
import com.example.yiwei.crm.data.GetDockData;
import com.example.yiwei.crm.entity.dockingEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.util.ZhengZhe;
import com.example.yiwei.crm.view.activity.areActivity.ProvinceActivity;
import com.example.yiwei.crm.view.activity.customerActivity.CustomerAddActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CoordinationAddActivity extends BaseActivity {

    private Spinner spinner_manager;
    private EditText edit_docking_name,edit_docking_mechanism,edit_mechanism_attribute,edit_department,
            edit_professional_title,edit_phone_number,edit_additional ,edit_xadress,edit_jd;
    private TextView txt_address;
    private Button btn_show;
    private ImageView img_back,img_commit;
    private JSONObject mJsonObj;
    private String Filename;
    private List<String> name_list=new ArrayList<>();
    private TextView mtCity;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCiry = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPickerView<String> mOpv;
    String tx;
    List<managerEntity> managerList;
    private ArrayAdapter adapter1;
    private String managerName;
    private int manager_id;
    List<com.example.yiwei.crm.entity.dockingEntity> dockinglist;
    private TextView txt_title;
    dockingEntity docking;
    dockingEntity dockingEntity;
    String manager_name;
    int dock_id;
    SharedPreferences sp;
    String pid;
    String pname="";
    String cid;
    String cname="";
    String aid;
    String aname="";
    List<dockingEntity> dockingList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coordination_add);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        img_back= (ImageView) findViewById(R.id.health_education_add_img_back);
        img_commit= (ImageView) findViewById(R.id.health_education_add_img_commit);
        btn_show= (Button) findViewById(R.id.health_education_add_btn_show);
        txt_address= (TextView) findViewById(R.id.health_education_add_txt_address);
        edit_docking_name= (EditText) findViewById(R.id.health_education_add_edit_docking_name);
        edit_docking_mechanism= (EditText) findViewById(R.id.health_education_add_edit_docking_mechanism);
        edit_mechanism_attribute= (EditText) findViewById(R.id.health_education_add_edit_mechanism_attribute);
        edit_department= (EditText) findViewById(R.id.health_education_add_edit_department);
        edit_professional_title= (EditText) findViewById(R.id.health_education_add_edit_professional_title);
        edit_phone_number= (EditText) findViewById(R.id.health_education_add_edit_phone_number);
        edit_additional= (EditText) findViewById(R.id.health_education_add_edit_additional);
        edit_xadress = (EditText) findViewById(R.id.health_education_add_edit_xadress);
        edit_jd = (EditText) findViewById(R.id.health_education_add_edit_jd);
        spinner_manager= (Spinner) findViewById(R.id.health_education_add_spinner_manager);
        txt_title= (TextView) findViewById(R.id.healt_education_add_txt_title);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        docking= GetDock.get();

//        dock_id=docking.getDocking_id();
        initJsonData(this);
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<String>(this);
        // 设置标题
        mOpv.setTitle("选择城市");
        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCiry, mListArea, true);
        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);
        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);
        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                tx = mListProvince.get(options1) + mListCiry.get(options1).get(option2) + mListArea.get(options1).get(option2).get(options3);
                txt_address.setText(tx);

            }
        });
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CoordinationAddActivity.this, ProvinceActivity.class);
                GetAreData.pname=null;
                GetAreData.aname = null;
                GetAreData.cname = null;
                GetAreData.pid = null;
                GetAreData.cid = null;
                GetAreData.aid = null;
                startActivity(intent);
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            txt_title.setText("修改协作人");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin",sp.getString("admin",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,json);
                for (int i=0;i<managerList.size();i++){
                    Log.d("aaa",managerList.get(i).toString());
                }
                for (int i2=0;i2<managerList.size();i2++){
                    name_list.add( managerList.get(i2).getManager_name());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter1 = new ArrayAdapter(CoordinationAddActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner,name_list);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_manager.setAdapter(adapter1);
                        spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                managerName=spinner_manager.getSelectedItem().toString();
                                for (int i1 = 0;i1<managerList.size();i1++){
                                    if (managerName.equals(managerList.get(i1).getManager_name())){
                                        manager_id = Integer.valueOf(managerList.get(i1).getManager_id());
                                    }
                                }
                                if ("update".equals(getIntent().getStringExtra("tag"))){
                                    showMessage();
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }
                });
            }
        }).start();

        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Toast.makeText(CoordinationAddActivity.this, "aa"+txt_address.getText().toString(), Toast.LENGTH_SHORT).show();
                if (txt_address.getText().toString().equals("")||edit_docking_name.getText().toString().equals("")) {
                    Toast.makeText(CoordinationAddActivity.this, "请填写行政区域和姓名！", Toast.LENGTH_SHORT).show();
                }else if (!"".equals(edit_phone_number.getText().toString())&& !ZhengZhe.phone(edit_phone_number.getText().toString())){
                    Toast.makeText(CoordinationAddActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }else {
                    add();
                }
            }
        });
    }
    public void add(){
        img_commit.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);

                try {
                    if ("update".equals(getIntent().getStringExtra("tag"))) {
                        docking = GetDock.get();
                        object.put("KXA01", docking.getDocking_id());
                        object.put("addoredit", "edit");
                    } else {
                        object.put("addoredit", "add");
                    }
                    object.put("KXA15", managerName);
                    object.put("KXA28", manager_id);
                    object.put("KXA02", edit_docking_name.getText().toString());
                    object.put("KXA03", edit_docking_mechanism.getText().toString());
                    object.put("KXA04", edit_mechanism_attribute.getText().toString());
                    object.put("KXA05", edit_department.getText().toString());
                    object.put("KXA06", edit_professional_title.getText().toString());
                    object.put("KXA08", edit_phone_number.getText().toString());
                    object.put("KXA29", txt_address.getText().toString());
                    object.put("REK01", edit_additional.getText().toString());
//                                object.put("KXA17", pid);
                    object.put("CID03", sp.getString("CID03", null));
                    if (!pname.equals("")){
                        object.put("KXA17", pid);
                        object.put("KXA18",pname);
                    }
                    if (!cname.equals("")){
                        object.put("KXA19", cid);
                        object.put("KXA20",cname);
                    }
                    if (!aname.equals("")){
                        object.put("KXA21", aid);
                        object.put("KXA22",aname);
                    }
                    object.put("KXA27", edit_jd.getText().toString());
                    object.put("KXA29", edit_xadress.getText().toString());
                    String json = object.toString();
                    String result;
                    result = NetWorkUtils.getCount(baseClass.edit_coordianation_URL, json);
                    JSONObject object1 = new JSONObject(result);
                    String boolen = object1.getString("ifsuccess");
                    if ("true".equals(boolen)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                dockDao dockDao = new dockDaoImpl();
                                if ("update".equals(getIntent().getStringExtra("tag"))) {
                                    GetDock.create();
                                    Log.d("aa", docking.getDocking_id() + "");
                                    GetDock.dockingEntity = dockDao.queryAllCoordinationdockMessage(baseClass.find_coordination_url_d + docking.getDocking_id(), null);
                                    Log.d("aa", GetDock.dockingEntity.toString());
                                    if (GetDock.dockingEntity != null) {
                                        finish();
                                    }
                                } else {
                                    finish();
                                }
                            }
                        }).start();
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                img_commit.setVisibility(View.VISIBLE);
                                Toast.makeText(CoordinationAddActivity.this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
    public void showMessage(){
        docking= GetDock.get();
        edit_department.setText(docking.getDepartment());
        edit_docking_name.setText(docking.getDocking_name());
        edit_docking_mechanism.setText(docking.getDocking_mechanism());
        edit_mechanism_attribute.setText(docking.getMechanism_attribute());
        edit_professional_title.setText(docking.getProfessional_title());
        edit_phone_number.setText(docking.getPhone_number());
//        System.out.print("iuuyyyy"+docking.getPname() + docking.getCname() + docking.getAname()+"llll");
        if (docking.getAname()!=null&&docking.getPname()!=null&&docking.getCname()!=null) {
            txt_address.setText(docking.getPname() + docking.getCname() + docking.getAname());
        }
        edit_additional.setText(docking.getAddtional_remark());
        edit_xadress.setText(docking.getAddress());
        edit_jd.setText(docking.getJd());
        SpinnerAdapter spadapter2 = spinner_manager.getAdapter();
        for (int i=0;i<managerList.size();i++) {
            if (docking.getManager_id() == managerList.get(i).getManager_id()) {
                manager_name =managerList.get(i).getManager_name();
            }
        }
        if (docking.getManager()!=null){
            for (int i = 0;i<spadapter2.getCount();i++){
                if (docking.getManager().equals(spadapter2.getItem(i).toString())){
                    spinner_manager.setSelection(i);
                }
            }
        }
    }
    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private void initJsonData(Context context) {
        Filename = "city.json";
        try {
            StringBuffer sb = new StringBuffer();
            AssetManager am = context.getAssets();
            InputStream is = am.open(Filename);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "GBK"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Json数据，并释放Json对象
     */
    private void initJsonDatas() {
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.getString("name");
                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.getString("name");
                    options2Items_01.add(city);// 添加市数据
                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    JSONArray jsonAs = jsonC.getJSONArray("area");
                    for (int k = 0; k < jsonAs.length(); k++) {
                        options3Items_01_01.add(jsonAs.getString(k));// 添加区数据
                    }
                    options3Items_01.add(options3Items_01_01);
                }
                mListProvince.add(province);// 添加省数据
                mListCiry.add(options2Items_01);
                mListArea.add(options3Items_01);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetAreData.pname!=null){
            pid = GetAreData.pid;
            pname = GetAreData.pname;
            cid = GetAreData.cid;
            cname = GetAreData.cname;
            aid = GetAreData.aid;
            aname =GetAreData.aname;
            txt_address.setText(pname+cname+aname);
        }
    }
}
